package com.ktgj.customer.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * 获取汉字全拼
 * */
public class ChineseCharacterUtil {
    /**
     * 将汉字转成全拼或首拼
     * */
    public static String convertHanzi2Pinyin(String hanzi){

        String regExp = "^[\u4E00-\u9FFF]+$";
        StringBuffer sb = new StringBuffer();
        if (hanzi == null || "".equals(hanzi.trim())){
            return "";
        }
        String pinyin = "";
        for (int i = 0 ; i < hanzi.length() ; i++){
            char unit = hanzi.charAt(i);
            if (match(String.valueOf(unit), regExp)){//是汉字，则转拼音
                pinyin = convertSingleHanzi2Pinyin(unit);
                sb.append(pinyin);
            }
            else {
                sb.append(unit);
            }
        }
        return sb.toString();
    }

    /**
     * 将单个汉字转成拼音
     * */
    private static String convertSingleHanzi2Pinyin(char hanzi){
        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        String[] res;
        StringBuffer sb = new StringBuffer();
        try {
            res = PinyinHelper.toHanyuPinyinStringArray(hanzi, outputFormat);
            sb.append(res[0]);//对于多音字，只能用第一个拼音
        }catch (Exception e){
            e.printStackTrace();
            return "";
        }
        return sb.toString();
    }

    /**
     * 判断源字符串与正则表达式是否匹配
     * */
    public static boolean match(String str, String regex){
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(str);
        return matcher.find();
    }
}
